﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.XPath;
using SaleManagement.Web.App_Code;

namespace SaleManagement.Web.Controls
{
  public partial class AdminSubMenu : BaseControl
  {
    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!Page.IsPostBack && !Page.IsCallback)
      {
        lrSubMenuTitle.Text = SelectedMenuItemTitle;
        ShowMenu();
      }
    }

    protected void rptMenu_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
      if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
      {
        string path = Request.Url.AbsolutePath;
        string url = Request.Url.ToString();
        string ext = string.Empty;
        if (url.IndexOf('?') > 0)
        {
          ext = url.Substring(url.IndexOf('?'));
        }
        string currentPage = path.Substring(path.LastIndexOf('/') + 1);
        currentPage = currentPage.Substring(0, currentPage.IndexOf(".aspx") + 5);
        XPathNavigator xmlPath = ((IXPathNavigable)e.Item.DataItem).CreateNavigator();
        XmlElement element = (XmlElement)xmlPath.UnderlyingObject;
        if (element != null)
        {
          HtmlControl li = e.Item.FindControl("liMenuItem") as HtmlControl;
          HtmlControl lnk = e.Item.FindControl("lnkMenuItem") as HtmlControl;
          if (lnk.Attributes["href"].Contains(currentPage))
          {
            li.Attributes["class"] = "active";
            lnk.Attributes["class"] = "active";
            #region Check User Permission
            if (!currentPage.Contains("login.aspx") && !currentPage.Contains("errorpage.aspx"))
            {
              int permissId = 0;
              int.TryParse(element.GetAttribute("PermissionId"), out permissId);
              if (!HasPermission(permissId))
              {
                (Page as BasePage).ErrorMessage = "Bạn không có quyền truy cập vào trang này.";
                Response.Redirect(element.GetAttribute("Redirect"));
              }
              else
              {
                (Page as BasePage).ErrorMessage = string.Empty;
              }
            }

            #endregion
          }

          #region Check Permission
          li.Visible = false;
          int permissionId = 0;
          int.TryParse(element.GetAttribute("PermissionId"), out permissionId);
          if (permissionId <= 0 || HasPermission(permissionId))
          {
            li.Visible = true;
          }
          #endregion
        }

      }

    }
    #endregion

    #region Methods
    private void ShowMenu()
    {
      dsMenu.XPath = "MenuItems/" + SelectedMenuItem + "/SubMenu";
      rptMenu.DataBind();
    }
    #endregion
  }
}